package com.dictionary.hi;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.custom.tab.AbstractTabRootManager;
import com.custom.tab.AbstractViewController;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class UploadViewController extends AbstractViewController {

	private MainTabHostActivity mainTabHostActivity;
	private TextView tv;
	private Button b;
	private int serverResponseCode = 0;
	ProgressDialog dialog = null;

	private static final int SELECT_PICTURE = 1;

	private String selectedImagePath;
	private ImageView img;
	private View v;

	public UploadViewController(AbstractTabRootManager tabRootManager,
			Bundle args) {
		super(tabRootManager, R.layout.vc_upload);
		try {
			mainTabHostActivity = (MainTabHostActivity) getActivity();
			v = getView();
			img = (ImageView) v.findViewById(R.id.ImageView01);

			// *************************

			b = (Button) v.findViewById(R.id.but);
			tv = (TextView) v.findViewById(R.id.tv);
			tv.setText("");

			b.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					if (tv.getText().toString()==""){
						Toast.makeText(mainTabHostActivity,
								"اختر الصورة", Toast.LENGTH_LONG)
								.show();
					}
					else{
					dialog = ProgressDialog.show(mainTabHostActivity, "",
							"إرسال الصورة...", true);
					new Thread(new Runnable() {
						public void run() {
							mainTabHostActivity.runOnUiThread(new Runnable() {
								public void run() {
									// tv.setText("uploading started.....");
								}
							});
							int response = uploadFile(tv.getText().toString());
							System.out.println("RES : " + response);
						}
					}).start();
						}
					}
			});
			
			v.findViewById(R.id.Button01).setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					onOpenGalleryClick(v);
				}
			});
			v.findViewById(R.id.butinfo).setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					onInfoClick(v);
				}
			});

			// final Intent intent = mainTabHostActivity.getIntent();
			// String action = intent.getAction();
			// String type = intent.getType();
			//
			// if (Intent.ACTION_SEND.equals(action) && type != null) {
			// if (type.startsWith("image/")) {
			// img.setImageURI((Uri)
			// intent.getParcelableExtra(Intent.EXTRA_STREAM));
			// tv.setText(getPath((Uri)
			// intent.getParcelableExtra(Intent.EXTRA_STREAM)));
			// }
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == mainTabHostActivity.RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				// selectedImagePath = getPath(selectedImageUri).replace("/mnt",
				// "");
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				img.setImageURI(selectedImageUri);
				tv.setText(selectedImagePath);
			}
		}
	}

	public String getPath(Uri uri) {
		String ret = null;
		try {
			Cursor cursor = null;
			try {
				String[] projection = { MediaStore.Images.Media.DATA };
				cursor = mainTabHostActivity.managedQuery(uri, projection, null,
						null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				ret = cursor.getString(column_index);
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				if(cursor!=null){
					cursor.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ret;
	}

	public int uploadFile(String sourceFileUri) {
		String upLoadServerUri = "http://67.202.79.82/tweetpicar/upload/upload_image.php?currentid=NewImAgEs20121433";
		String fileName = sourceFileUri;

		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;
		File sourceFile = new File(sourceFileUri);
		if (!sourceFile.isFile()) {
			Toast.makeText(mainTabHostActivity,
					"اختر الصورة", Toast.LENGTH_LONG)
					.show();
			return 0;
		}
		try { // open a URL connection to the Servlet
			FileInputStream fileInputStream = new FileInputStream(sourceFile);
			URL url = new URL(upLoadServerUri);
			conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
																// connection to
																// the URL
			conn.setDoInput(true); // Allow Inputs
			conn.setDoOutput(true); // Allow Outputs
			conn.setUseCaches(false); // Don't use a Cached Copy
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("ENCTYPE", "multipart/form-data");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			conn.setRequestProperty("uploaded_file", fileName);
			dos = new DataOutputStream(conn.getOutputStream());

			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
					+ fileName + "\"" + lineEnd);
			dos.writeBytes(lineEnd);

			bytesAvailable = fileInputStream.available(); // create a buffer of
															// maximum size

			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// read file and write it into form...
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			// send multipart form data necesssary after file data...
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// Responses from the server (code and message)
			serverResponseCode = conn.getResponseCode();
			String serverResponseMessage = conn.getResponseMessage();

			Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage
					+ ": " + serverResponseCode);
			if (serverResponseCode == 200) {
				mainTabHostActivity.runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(mainTabHostActivity,
								"شكراً , تم إستقبال الصورة", Toast.LENGTH_LONG)
								.show();
						img.setImageDrawable(null);
						tv.setText("");
					}
				});
			}

			// close the streams //
			fileInputStream.close();
			dos.flush();
			dos.close();

		} catch (MalformedURLException ex) {
			dialog.dismiss();
			ex.printStackTrace();
			Toast.makeText(mainTabHostActivity, "MalformedURLException",
					Toast.LENGTH_SHORT).show();
			Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
		} catch (Exception e) {
			dialog.dismiss();
			e.printStackTrace();
			Toast.makeText(mainTabHostActivity,
					"Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
			Log.e("Upload file to server Exception",
					"Exception : " + e.getMessage(), e);
		}
		dialog.dismiss();
		return serverResponseCode;
	}

	public void onOpenGalleryClick(View v) {
		try {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(Intent.createChooser(intent, "Select Picture"),
					SELECT_PICTURE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onInfoClick(View v) {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					mainTabHostActivity);
			builder.setMessage(getString(R.string.disclaimer))
					.setCancelable(false)
					.setPositiveButton("موافق",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});

			AlertDialog alert = builder.create();
			alert.setTitle("شروط المشاركة");
			alert.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}